/**
 * Filename: BaseApplication.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/2/23 16:27
 */
package com.github.postsanf.yinian;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.util.DisplayMetrics;
import android.util.Log;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNHistory;
import com.github.postsanf.yinian.bean.YNMember;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.utils.ImagePipelineConfigFactory;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.YNDoSecretUtils;
import com.hyphenate.chat.EMMessage;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.qiniu.android.common.Zone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.persistent.FileRecorder;
import com.qiniu.android.utils.UrlSafeBase64;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import cn.beecloud.BeeCloud;
import sweetcamera.util.FileUtil;

public class BaseApplication extends MultiDexApplication {
    public static Context applicationContext;
    private YNUser curUser = new YNUser();
    private UploadManager uploadManager;
    private String upToken;
    private int curID = 0;
    private int curGid;
    private String curgimid;
    private SharedPreferences sp_login;
    private SharedPreferences sp_data;
    private IWXAPI wxApi;
    private YNAlbum curInviteAlbum = new YNAlbum();

    private static BaseApplication mInstance = null;
    public static String currentUserNick = "";

    public ArrayList<ISkinUpdate> mActivitys = new ArrayList();
    private List<YNMember> memberList = new ArrayList<>();
    private List<EMMessage> emMessageList = new ArrayList<>();
    private List<YNHistory> emHistoryList = new ArrayList<>();

    public List<YNHistory> getEmHistoryList() {
        return emHistoryList;
    }

    public void setEmHistoryList(List<YNHistory> emHistoryList) {
        this.emHistoryList = emHistoryList;
    }

    public List<EMMessage> getEmMessageList() {
        return emMessageList;
    }

    public void setEmMessageList(List<EMMessage> emMessageList) {
        this.emMessageList = emMessageList;
    }

    public YNAlbum getCurInviteAlbum() {
        return curInviteAlbum;
    }

    public void setCurInviteAlbum(YNAlbum curInviteAlbum) {
        this.curInviteAlbum = curInviteAlbum;
    }

    public List<YNMember> getMemberList() {
        return memberList;
    }

    public void setMemberList(List<YNMember> memberList) {
        this.memberList = memberList;
    }

    public String getUpToken() {
        return upToken;
    }

    public void setUpToken(String upToken) {
        this.upToken = upToken;
    }

    public UploadManager getUploadManager() {
        return uploadManager;
    }

    public SharedPreferences getSp_login() {
        return sp_login;
    }

    public void setSp_login(SharedPreferences sp_login) {
        this.sp_login = sp_login;
    }

    public SharedPreferences getSp_data() {
        return sp_data;
    }

    public void setSp_data(SharedPreferences sp_data) {
        this.sp_data = sp_data;
    }

    public int getCurGid() {
        return curGid;
    }

    public void setCurGid(int curGid) {
        this.curGid = curGid;
    }

    public String getCurgimid() {
        return curgimid;
    }

    public void setCurgimid(String curgimid) {
        this.curgimid = curgimid;
    }

    public YNUser getCurUser() {
        return curUser;
    }

    public void setCurUser(YNUser curUser) {
        this.curUser = curUser;
    }

    public int getCurID() {
        int res = 0;
        try {
            res = curID > 0 ? curID : Integer.parseInt(YNDoSecretUtils.getSecretStr((getSp_login().getString(getString(R.string.LID), "0"))));
        } catch (NumberFormatException e) {
        }
        return res;
    }

    public void setCurID(int curID) {
        this.curID = curID;
    }

    public IWXAPI getWxApi() {
        if (wxApi == null) {
            wxApi = WXAPIFactory.createWXAPI(this, getString(R.string.WX_APP_ID));
            wxApi.registerApp(getString(R.string.WX_APP_ID));
        }
        return wxApi;
    }

    public void setWxApi(IWXAPI wxApi) {
        this.wxApi = wxApi;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public void clearAllData() {
        curID = 0;
        curGid = 0;
        YNSingleton.getInstance().clearAlbumList();
    }

    public static BaseApplication getInstance() {
        return mInstance;
    }

    private static final String ACTION_PEOPLESPACE_NOTICE1 = "com.yinian.action.peoplespace1";
    private static final String ACTION_PEOPLESPACE_NOTICE2 = "com.yinian.action.peoplespace2";
    private static final String ACTION_PEOPLESPACE_NOTICE3 = "com.yinian.action.peoplespace3";
    private static final String ACTION_PEOPLESPACE_NOTICE4 = "com.yinian.action.peoplespace4";

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.SKIN_ACTION);
        myIntentFilter.addAction(ACTION_PEOPLESPACE_NOTICE1);
        myIntentFilter.addAction(ACTION_PEOPLESPACE_NOTICE2);
        myIntentFilter.addAction(ACTION_PEOPLESPACE_NOTICE3);
        myIntentFilter.addAction(ACTION_PEOPLESPACE_NOTICE4);
        this.registerReceiver(SkinBroadCastReceiver, myIntentFilter);
    }

    ArrayList<Activity> list = new ArrayList<Activity>();


    /**
     * Activity关闭时，删除Activity列表中的Activity对象
     */
    public void removeActivity(Activity a) {
        list.remove(a);
    }

    /**
     * 向Activity列表中添加Activity对象
     */
    public void addActivity(Activity a) {
        list.add(a);
    }

    /**
     * 关闭Activity列表中的所有Activity
     */
    public void finishActivity() {
        for (Activity activity : list) {
            if (null != activity) {
                activity.finish();
            }
        }
        //杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static int mScreenWidth = 0;
    public static int mScreenHeight = 0;
    public static BaseApplication CONTEXT;

    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = this;
        mInstance = this;
        CONTEXT = this;
        sp_data = getSharedPreferences(getString(R.string.SP_DATA), Context.MODE_PRIVATE);
        sp_login = getSharedPreferences(getString(R.string.SP_LOGIN), Context.MODE_PRIVATE);
        registerBoradcastReceiver();
        UMShareAPI.get(this);
        //友盟DEBUG
//        Config.DEBUG = true;
//        QueuedWork.isUseThreadPool = false;
        //友盟启用捕捉异常,设置该CrashHandler为程序的默认处理器
//        UnCeHandler catchExcep = new UnCeHandler(this);
//        Thread.setDefaultUncaughtExceptionHandler(catchExcep);
        DemoHelper.getInstance().init(applicationContext);//环信
        initFrescoLoader();
        initImageLoader(this);
        initUpImage();
        // 微信平台的配置
        PlatformConfig.setWeixin(getString(R.string.WX_APP_ID), getString(R.string.WX_APP_SECRET));
        PlatformConfig.setQQZone("1105020902", "KsyG6XkQPE2bOvqZ");
        //Beecloud
        BeeCloud.setSandbox(false);//开启测试模式
        BeeCloud.setAppIdAndSecret("2e5f6283-47cd-4baa-9821-faeafc54a279",
                "439b4971-3456-4740-91de-78fd28ba5379");
        //相机
        DisplayMetrics mDisplayMetrics = getApplicationContext().getResources()
                .getDisplayMetrics();
        mScreenWidth = mDisplayMetrics.widthPixels;
        mScreenHeight = mDisplayMetrics.heightPixels;
        FileUtil.initFolder();
        //        String skinPath = SkinConfig.getInstance(getApplicationContext()).getSkinResourcePath();
//        if (!TextUtils.isEmpty(skinPath) && new File(skinPath).exists()) {
//            //如果已经换皮肤，那么第二次进来时，需要加载该皮肤
//            SkinPackageManager.getInstance(this).loadSkinAsync(skinPath, null);
//        }

    }


    // Fresco加载初始化
    private void initFrescoLoader() {
        // 配置Fresco 渐进式加载
//		ImagePipelineConfig imagePipelineConfig = ImagePipelineConfig.newBuilder(this)
//				.setDownsampleEnabled(true)
//				.setProgressiveJpegConfig(new SimpleProgressiveJpegConfig())
//				.build();
        Fresco.initialize(this, ImagePipelineConfigFactory.getOkHttpImagePipelineConfig(this));
    }

    // 初始化图片处理
    private void initImageLoader(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .memoryCacheExtraOptions(480, 800)
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .denyCacheImageMultipleSizesInMemory()
//                .memoryCache(new UsingFreqLimitedMemoryCache(10 * 1024 * 1024))
                .memoryCache(new WeakMemoryCache())
                .memoryCacheSize(10 * 1024 * 1024)
                .memoryCacheSizePercentage(13)
                .diskCacheSize(50 * 1024 * 1024).diskCacheFileCount(100)
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000))
                .build();
        ImageLoader.getInstance().init(config);
    }

    // 初始化图片上传
    private void initUpImage() {
        // 参数配置
        Configuration config = null;
        try {
            config = new Configuration.Builder()
                    .recorder(new FileRecorder(
                                    this.getFilesDir() + "/QiniuAndroid"),
                            new KeyGenerator() {
                                //  指定一个进度文件名，用文件key，文件路径和最后修改时间做hash
                                // generator
                                @Override
                                public String gen(String key, File file) {
                                    String recorderName = System.currentTimeMillis() + ".progress";
                                    try {
                                        recorderName = UrlSafeBase64.encodeToString(SizeFormat.sha1(key + ":" + file
                                                .getAbsolutePath() + ":" + file.lastModified())) + ".progress";
                                    } catch (NoSuchAlgorithmException e) {
                                        Log.e("QiniuLab", e.getMessage());
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e("QiniuLab", e.getMessage());
                                    }
                                    return recorderName;
                                }
                            })
                    .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认 256K
                    .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认 512K
                    .connectTimeout(90) // 链接超时。默认 10秒
                    .responseTimeout(180) // 服务器响应超时。默认 60秒
                    .zone(Zone.zone0) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。默认 Zone.zone0
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
        }
        uploadManager = new UploadManager();
    }


    public boolean saveObject(Serializable ser, String file) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = openFileOutput(file, MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(ser);
            oos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                oos.close();
            } catch (Exception e) {
            }
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }

    private boolean isReadDataCache(String cachefile) {
        return readObject(cachefile) != null;
    }

    public Serializable readObject(String file) {
        if (!isExistDataCache(file))
            return null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = openFileInput(file);
            ois = new ObjectInputStream(fis);
            return (Serializable) ois.readObject();
        } catch (FileNotFoundException e) {
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof InvalidClassException) {
                File data = getFileStreamPath(file);
                data.delete();
            }
        } finally {
            try {
                ois.close();
            } catch (Exception e) {
            }
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    private boolean isExistDataCache(String cachefile) {
        boolean exist = false;
        File data = getFileStreamPath(cachefile);
        if (data.exists())
            exist = true;
        return exist;
    }


    // 广播接收
    public BroadcastReceiver SkinBroadCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.SKIN_ACTION:
                    changeSkin();
                    break;
                case ACTION_PEOPLESPACE_NOTICE1:
                    if (intent != null) {
                        YNAlbum ynalbum = (YNAlbum) intent.getSerializableExtra("ynalbum");
                        YNSingleton.getInstance().setCurAlbum(ynalbum);
                        setCurGid(ynalbum.getGroupid());
                        startActivity(new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        Intent psintent = new Intent(context, PeopleSpaceActivity2.class);
//                        psintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        psintent.putExtra(ACTIONs.aAddData, true);
//                        context.startActivity(psintent);
                        ynalbum.setGmnotify(0);
//                        startActivity(new Intent(context, TimeImpressActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        UIHelper.collapseStatusBar(context);
                    }
                    break;
                case ACTION_PEOPLESPACE_NOTICE2:
                    if (intent != null) {
                        YNAlbum ynalbum = (YNAlbum) intent.getSerializableExtra("ynalbum");
                        YNSingleton.getInstance().setCurAlbum(ynalbum);
                        setCurGid(ynalbum.getGroupid());
                        startActivity(new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        Intent psintent = new Intent(context, PeopleSpaceActivity2.class);
//                        psintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        psintent.putExtra(ACTIONs.aAddData, true);
//                        startActivity(psintent);
                        ynalbum.setGmnotify(0);
//                        startActivity(new Intent(context, TimeImpressActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        UIHelper.collapseStatusBar(context);
                    }
                    break;
                case ACTION_PEOPLESPACE_NOTICE3:
                    if (intent != null) {
                        YNAlbum ynalbum = (YNAlbum) intent.getSerializableExtra("ynalbum");
                        YNSingleton.getInstance().setCurAlbum(ynalbum);
                        setCurGid(ynalbum.getGroupid());
                        startActivity(new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        Intent psintent = new Intent(context, PeopleSpaceActivity2.class);
//                        psintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        psintent.putExtra(ACTIONs.aAddData, true);
//                        startActivity(psintent);
                        ynalbum.setGmnotify(0);
//                        startActivity(new Intent(context, TimeImpressActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        UIHelper.collapseStatusBar(context);
                    }
                    break;
                case ACTION_PEOPLESPACE_NOTICE4:
                    if (intent != null) {
                        YNAlbum ynalbum = (YNAlbum) intent.getSerializableExtra("ynalbum");
                        YNSingleton.getInstance().setCurAlbum(ynalbum);
                        setCurGid(ynalbum.getGroupid());
                        startActivity(new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        Intent psintent = new Intent(context, PeopleSpaceActivity2.class);
//                        psintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        psintent.putExtra(ACTIONs.aAddData, true);
//                        startActivity(psintent);
                        ynalbum.setGmnotify(0);
//                        startActivity(new Intent(context, TimeImpressActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//                        UIHelper.collapseStatusBar(context);
                    }
                    break;

            }
        }
    };

    @Override
    public void onTerminate() {
        this.unregisterReceiver(SkinBroadCastReceiver);
        super.onTerminate();
    }

    public void changeSkin() {
        for (ISkinUpdate skin : mActivitys) {
            skin.updateTheme();
        }
    }
}
